from baseview import BaseView
from ..devicetree import DeviceTree
from ..bases import widgets
from .. import editors

class CueStackView(BaseView):
    topwidget_name = 'Cue Stacks'
    topwidget_cls = widgets.HPane
    def __init__(self, **kwargs):
        self.topwidget = widgets.VBox()
        super(CueStackView, self).__init__(**kwargs)
        
        self.stack_editor = None
        
        frame = self.make_child_widget(widgets.Frame, 'frame1', label='Stacks')
        col_names = ['id', 'Index', 'name']
        col_types = [str, int, str]
        obj_names = ['Stack']
        self.stack_list = DeviceTree(col_names=col_names, col_types=col_types, obj_names=obj_names, child_name_attr='none', 
                                     show_dicts=False, base_dict=self.MainController.CueStacks, used_columns=[1, 2])
        self.stack_list.widget.connect('selection_changed', self.on_stack_list_selection_changed)
        frame.pack_start(self.stack_list.widget.topwidget, expand=True)
        
        hbox = widgets.HBox()
        d = {'btnNewStack':'New Cue Stack', 'btnDelStack':'Delete'}
        for k, v in d.iteritems():
            btn = self.make_child_widget(widgets.Button, k, label=v)
            btn.connect('clicked', self.on_stack_list_btns_clicked, k)
            hbox.pack_start(btn)
        frame.pack_start(hbox)
        
        self.topcontainer.pack_start(frame)
        
        #self.MainController.connect('child_added', self.on_mc_child_added)
        signals = ['child_added', 'child_removed', 'child_index_changed']
        self.MainController.CueStacks.bind(**dict(zip(signals, [self.on_mc_child_update]*len(signals))))
        
        self.topwidget.show_all()
        
    def unlink(self):
        self.MainController.unbind(self.on_mc_child_update)
        super(CueStackView, self).unlink()
    
    def set_current_stack(self, obj):
        if self.stack_editor is not None:
            self.remove_editor(self.stack_editor)
        if obj is not None:
            self.add_editor(editors.CueStackEditor, 'stack_editor', stack=obj)
            self.topcontainer.pack_start(self.stack_editor.topwidget, expand=True)
    
    def on_stack_list_selection_changed(self, **kwargs):
        obj = kwargs.get('obj')
        state = kwargs.get('state')
        if state and hasattr(obj, 'id'):
            self.set_current_stack(obj)
        
    def on_stack_list_btns_clicked(self, btn, key):
        if key == 'btnNewStack':
            stack = self.MainController.add_CueStack(name='New Stack')
            self.stack_list.tree.set_selection(stack.id)
        elif key == 'btnDelStack':
            if self.stack_editor:
                stack = self.stack_editor.stack
                self.set_current_stack(None)
                self.MainController.del_CueStack(id=stack.id)
                
    def on_mc_child_update(self, **kwargs):
        self.stack_list.tree.refresh_all()
